import React, { useState, useEffect, useRef } from 'react'
import '@wangeditor/editor/dist/css/style.css'
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Dropdown,
  Menu, Space,
  Button, message,
  Popconfirm, Drawer,
  Form,
  Input,
  Radio,
  Select,
  Cascader,
  DatePicker,
  InputNumber,
  TreeSelect,
  Switch,
  Checkbox,
  Upload,
  Card,
  UploadProps,
  Pagination,
} from 'antd';
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IButtonMenu, IDomEditor, IEditorConfig, IToolbarConfig, Boot } from '@wangeditor/editor'
import "./newartical.less"
import markdownModule from '@wangeditor/plugin-md'
import { getImgList, getImgListpage, getInnerHtml, getlebal, gettagvalue } from '@/api/newartical';
import { history } from 'umi';
import request from '@/utils/request';
import { useForm } from 'antd/es/form/Form';
import { Header } from 'antd/lib/layout/layout';
import { newActicle } from '@/utils/works';
const { Meta } = Card;
const { Option } = Select;
type Props = {}

//设置form表单
const { RangePicker } = DatePicker;
const { TextArea } = Input;

class MyButtonMenu implements IButtonMenu {   // TS 语法
  // class MyButtonMenu {  
  title: string                     // JS 语法
  iconSvg: string
  tag: string
  constructor() {
    this.iconSvg = '<svg className="icon-wj" viewBox="0 0 1072 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3023" width="32" height="32"><path d="M491.9107146 202.62499973h209.1696427a88.39285674 88.39285674 0 0 1 88.39285675 88.39285757 32.1428573 32.1428573 0 1 0 64.28571459 0 152.67857136 152.67857136 0 0 0-152.67857134-152.67857135H491.9107146a32.1428573 32.1428573 0 1 0 0 64.28571378z m61.67410648 56.25000027L482.5491073 116.00000027a32.1428573 32.1428573 0 1 0-57.57589325 28.60714271l74.37053595 149.58482107a52.2321427 52.2321427 0 0 0 46.76785702 28.96875055H813.33928595A88.39285674 88.39285674 0 0 1 901.7321427 411.55357136v321.42857134a32.1428573 32.1428573 0 1 0 64.2857146 0V411.55357136A152.67857136 152.67857136 0 0 0 813.33928595 258.875h-259.75446487z m348.14732162 273.5357146V773.16071433a88.39285674 88.39285674 0 0 1-88.39285675 88.39285674H250.83928567A88.39285674 88.39285674 0 0 1 162.44642893 773.16071433V250.83928567A88.39285674 88.39285674 0 0 1 250.83928567 162.44642893h202.90178568a32.1428573 32.1428573 0 1 0 0-64.2857146H250.83928567A152.67857136 152.67857136 0 0 0 98.16071433 250.83928567v522.32142866A152.67857136 152.67857136 0 0 0 250.83928567 925.83928567h562.50000028a152.67857136 152.67857136 0 0 0 152.67857135-152.67857134v-240.74999973a32.1428573 32.1428573 0 1 0-64.2857146 0z" p-id="3024"></path></svg></svg>' // 可选
    this.tag = 'button'
    this.title = "打开文件"
  }
  // title: string;
  // title: string;
  // title: string;
  hotkey?: string | undefined;
  alwaysEnable?: boolean | undefined;
  width?: number | undefined;
  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {   // TS 语法
    // getValue(editor) {                              // JS 语法
    return true
  }
  // Boot.registerModule(markdownModule)
  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {  // TS 语法
    // isActive(editor) {                    // JS 语法
    return false
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {   // TS 语法
    // isDisabled(editor) {                     // JS 语法
    return false
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    // fileFlag = value
    if (typeof value === "string") {
      editor.insertText(value)

    }
    console.log(typeof (value), 'value')
    // console.log(fileFlag, 'editor');
  }

}
Boot.registerMenu({
  key: 'a1',
  factory() {
    return new MyButtonMenu()
  }
})

const Newartical = (props: Props) => {
  //上传图片
  const photo: UploadProps = {
    name: 'file',
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  //右侧设置的抽屉
  const [open, setOpen] = useState(false);

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
  //第二个抽屉
  const [openTwo, setOpenTwo] = useState(false);
  const showDrawerTwo = () => {
    setOpenTwo(true);
  };

  const onCloseTwo = () => {
    setOpenTwo(false);
  };

  const onFinishTwo = (values: newActicle) => {
    console.log('Success:', values);
  };
  const onFinishFailedTwo = (errorInfo: newActicle) => {
    console.log('Failed:', errorInfo);
  };
  //第二个抽屉图片内容
  const [imglist, setimglist] = useState([])
  const [page, setpage] = useState(0)
  // const [pages,setpages]=useState(page)
  useEffect(() => {
    (async () => {
      let res = await getImgList()
      setimglist(res.data.data[0])
      setpage(res.data.data[1])
    })()
  }, [])
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null)
  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
              查看
            </a>
          ),
          disabled: true,
        },
        {
          key: '2',
          label: (
            <a target="_blank" rel="noopener noreferrer" onClick={() => {
              value == "1" ? message.warn("请先输入标题") : showDrawer()
            }}>
              设置
            </a>
          ),
        },
        {
          key: '3',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
              保存草稿
            </a>
          ),
        },
        {
          key: '4',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
              删除
            </a>
          ),
          disabled: true,
        },
      ]}
    />
  );

  // 编辑器内容
  // const [html, setHtml] = useState('')
  Boot.registerModule(markdownModule)
  const tocBox=useRef(null)
  const [conect, setconect] = useState<IDomEditor|null>(null)
  const [low, setlow] = useState("")
  // 编辑器内容
  const [html, sethtml] = useState('<p>hello</p>')

  // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setTimeout(() => {
      sethtml(" ")
    }, 1500)
  }, [])

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    // toolbarKeys:["bold"],
    insertKeys: {
      index: 32,
      keys: "a1"
    }
  }  // TS 语法
  // console.log(editor?.getAllMenuKeys);
  // const toolbarConfig = { }                        // JS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    onChange(e) {
      const  headers = e.getElemsByTypePrefix("header");
      (tocBox.current as unknown as HTMLDivElement).innerHTML=headers.map(header=>{
        const text=(header.children[0] as newActicle).text
        const {id,type}=header as newActicle
        return `<li id="${id}" type="${type}">${text}</li>`
      }).join("")
    },
  }
  //点击toc滚动
  const handleTocClick=(e:newActicle)=>{
    if(e.target.tagName==="LI"){
      editor?.scrollToElem(e.target.id);
    }
  }
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  const [value, setvalue] = useState("1")

  //点击头部x号按钮
  const text = '确认关闭?如果有内容变更，请先保存';

  const confirm = () => {
    message.info('关闭成功.');
    history.push("/pages/work")
  };
  // 获取form表单数据
  const [form] = Form.useForm();
  // const [forminfo, setforminfo] = useState({ comments: false, recommended: false, digest: "", tags: [], password: "", pay: "" })
  //设置抽屉的form表单
  const onFinish = (values: newActicle) => {
    console.log(`"${form.getFieldsValue().tags.toString()}"`);

  };
  const onFinishFailed = (errorInfo: newActicle) => {
    console.log('Failed:', errorInfo);
  };
  // console.log(forminfo);

  //编辑or预览
  const [write, setwrite] = useState(false)
  const [writevalue, setwritevalue] = useState("编辑")
  //两栏观看
  const [twolan, settwolan] = useState(false)
  const [lanvalue, setlanvalue] = useState("两栏显示")
  //大纲
  const [outline, setoutline] = useState(false)
  const [outlinevalue, setoutlinevalue] = useState("大纲")

  //分类标签
  const [taglist, settaglist] = useState([])
  const [tags, settags] = useState([])
  useEffect(() => {
    (async () => {
      let res = await getlebal()
      settaglist(res.data.data)
      // let valuesl = await gettagvalue()
      // settags(res.data.data)
    })()
  }, [])

  // console.log(tags);
  //多选标签
  useEffect(() => {
    (async () => {
      let res = await gettagvalue()
      // settaglist(res.data.data)
      // let valuesl = await gettagvalue()
      settags(res.data.data)
    })()
  }, [])

  const children: React.ReactNode[] = [];
  {
    tags && tags.map((item: newActicle, index: number) => {
      return children.push(<Option key={item.id} value={item.id}>{item.label}</Option>)
    })
  }
  // console.log(taglist);

  const handleChange = (value: string[]) => {
    console.log(`selected ${value}`);
  };

  return (
    <div className='newartical'>
      <header>
        <Popconfirm
          placement="rightTop"
          title={text}
          onConfirm={confirm}
          okText="确认"
          cancelText="取消"
        >
          <Button className='closebtn'>x</Button>
        </Popconfirm>
        <input type="text" onChange={(e) => {
          setvalue(e.target.value);
        }} />
        <div className='fbbox'>
          <Button type='primary' className='releasebtn' onClick={() => {//
            // console.log(value, html);
            value == "1" ? message.warn("请先输入标题") :
              // console.log(form.getFieldsValue());

              request.post("http://111.67.198.176:8103/api/article", {
                title: value,
                content: conect,
                html: html,
                toc: low,
                status: "publish",
                isCommentable: form.getFieldsValue().comments,
                isRecommended: form.getFieldsValue().recommended,
                summary: form.getFieldsValue().digest,
                tags: `"${form.getFieldsValue().tags.toString()}"`,
                password: form.getFieldsValue().password,
                totalAmount: form.getFieldsValue().pay,
                cover: form.getFieldsValue().photo,
                category: form.getFieldsValue().classify
              }).then(res => {
                // console.log(res);
                message.success("发布成功")
              })
          }}>发布</Button>
          <Dropdown overlay={menu}>
            <a onClick={e => e.preventDefault()}>
              <Space>
                <svg className="icon-more" fill='#1890ff' viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2161" width="32" height="32"><path d="M288 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2162"></path><path d="M512 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2163"></path><path d="M736 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2164"></path></svg>
              </Space>
            </a>
          </Dropdown>
        </div>

      </header>
      <main>
        <div className='fwbmain' style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <div className='kheader'>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
            // style={{ borderBottom: '1px solid #ccc' }}
            />
            <p className='lan'>
              当前模式:<span onClick={() => {
                setwrite(!write)
                write ? setwritevalue("预览") : setwritevalue("编辑")
              }}>{writevalue}</span><span onClick={() => {
                settwolan(!twolan)
                twolan ? setlanvalue("退出两栏显示") : setlanvalue("两栏显示")
              }}>{lanvalue}</span><span onClick={() => {
                setoutline(!outline)
              }}>{outlinevalue}</span>
            </p>
          </div>

          <div className='writebox'>
            <Editor
              // id="fwbwrite"
              defaultConfig={editorConfig}
              value={" "}
              onCreated={setEditor}
              onChange={editor => sethtml(editor.getHtml())}
              mode="default"
              style={{ flex: "1", height: "100%", overflowY: 'auto', float: "left" }}
            />
            {
              twolan ? <></> : <div className='htmlinner' dangerouslySetInnerHTML={{ __html:html }} />
            }
            {
              outline ? <></> : <div className='lowbox' id="tocBox" ref={tocBox} onClick={(e)=>{
                handleTocClick(e)
              }}></div>
            }

          </div>
        </div>
      </main >
      <Drawer title="文章设置" width="500px" placement="right" onClose={onClose} open={open}>
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          layout="horizontal"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}

        // disabled={componentDisabled}
        >
          <Form.Item label="文章摘要" name="digest">
            <TextArea placeholder='请输入文章摘要' rows={4} />
          </Form.Item>
          <Form.Item label="访问密码" name="password">
            <Input.Password placeholder='输入后查看需要密码' />
          </Form.Item>
          <Form.Item label="付费查看" name="pay">
            <Input.Password placeholder='输入后需要支付的费用' />
          </Form.Item>
          <Form.Item label="开启评论" name="comments" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="首页推荐" name="recommended" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="选择分类" name="classify">
            <Select>
              {
                taglist && taglist.map((item: newActicle, index: number) => {
                  return <Option key={item.id} value={item.id}>{item.label}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="选择标签" name="tags">
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder="Please select"
              // defaultValue={['a10', 'c12']}
              onChange={handleChange}
            >
              {children}
            </Select>
          </Form.Item>
          <Form.Item label="文章封面" name="photo" valuePropName="fileList">
            <Upload action="/upload.do" listType="picture-card">
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            </Upload>
            <Input placeholder='或输入外部链接' />
          </Form.Item>
          <Form.Item label="" name="remove">
            <Button style={{ marginLeft: "75px" }}>移除</Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button onClick={() => {
              onClose()
            }} style={{ float: "right" }} type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer><div className=""></div>
      <Drawer width={800} className='drawerboxtwo' title="文件选择" placement="right" onClose={onCloseTwo} open={openTwo}>
        <p style={{ height: "30px", lineHeight: "30px", border: "1px #7aceff solid", backgroundColor: "#e6f7ff" }}>点击卡复制链接，点击图片查看大图</p>
        <Form
          className='formboxtwo'
          name="basic1"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinishTwo}
          onFinishFailed={onFinishFailedTwo}
          autoComplete="off"
        >
          <Form.Item
            label="文件名"
            name="filename"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="文件类"
            name="filetype"
          >
            <Input />
          </Form.Item>

          <Form.Item className='pricturebtn' wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button >
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className='prictruebox'>
          <p>
            <Upload {...photo}>
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
            {/* <Button>上传文件</Button> */}
          </p>
          <div className='pictruedown'>
            <div className='ppp'>
              {
                imglist && imglist.map((item: newActicle, index: number) => {
                  return <Card
                    hoverable
                    style={{ width: "20%", height: "200px", float: "left", margin: "10px 10px" }}
                    cover={<img alt="example" src={item.url} style={{ width: "100%", height: "150px" }} />}
                  >
                    <Meta description={item.filename} style={{ width: "100%", height: "50px", marginTop: "-20px" }} />
                  </Card>
                })
              }
            </div>
            <Pagination
              className='pppfy'
              // style={{ width: "100%", height: "35px" }}
              total={page}
              showSizeChanger={true}
              showLessItems
              // showSizeChanger
              // onShowSizeChange={onShowSizeChange}
              // onShowSizeChange={async(current, pageSize) => {
              //   console.log(current, pageSize);
              //   // let res = await getImgListpage(current, pageSize)
              //   // setimglist(res.data.data[0])
              //   // setpage(res.data.data[1])
              // }}
              defaultPageSize={12}
              // total={page}
              pageSizeOptions={[8, 12, 24, 36]}
              showTotal={total => `共有 ${page} 条`}
              onChange={async (current, pageSize) => {
                console.log(current, pageSize);
                let res = await getImgListpage(current, pageSize)
                setimglist(res.data.data[0])
                setpage(res.data.data[1])
              }}
            />
          </div>
        </div>
      </Drawer>
    </div >
  )
}

export default Newartical